package com.easy.frame.base.service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;

/**
 * swagger配置类
 *
 * @author zzf
 * @date 2020/6/29 14:38
 */
@Slf4j
@EnableSwagger2
@Configuration
@ConditionalOnProperty(prefix = "ef.enabled", value = "swagger", matchIfMissing = true)
@EnableConfigurationProperties(EasyFrameProperties.class)
public class SwaggerConfig {

    private final EasyFrameProperties properties;

    public SwaggerConfig(EasyFrameProperties properties) {
        this.properties = properties;
    }


    @Bean
    public Docket createRestApi() {

        //全局参数定义
        Parameter parameter = new ParameterBuilder().name("accessToken")
                .description("user login token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(properties.project.serverName)
                .apiInfo(apiInfo())
                .globalOperationParameters(Collections.singletonList(parameter))
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.swagger.basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(properties.swagger.title)
                .description(properties.swagger.description)
                //.termsOfServiceUrl()
                .version(properties.swagger.version)
                .build();
    }
}
